/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
    let res = new ListNode()
    let tail = res
    let carryNum = 0
    while (l1 || l2) {
        let num1 = l1?.val || 0
        let num2 = l2?.val || 0
        let sum = num1 + num2 + carryNum //两数相加再加上一位的进位
        carryNum = Math.floor(sum / 10) //计算给下一位的进位
        tail.next = new ListNode(sum % 10)
        tail = tail.next
        l1 = l1?.next || null
        l2 = l2?.next || null
    }
    //如果还有进位
    if (carryNum > 0) {
        tail.next = new ListNode(carryNum)
    }
    return res.next
};